
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class TransferJsonToLibSVM {
    public static void main(String[] args) {
        File f = new File("C:\\files\\dev\\LTP\\data\\tfidf.model\\json_feature.json");
        File libsvmFile = new File("C:\\files\\dev\\LTP\\data\\tfidf.model\\libsvm_feature");

        try {
            List<String> features = FileUtils.readLines(f);

            for (String str : features) {
                JSONObject obj = JSONObject.fromObject(str);

                String label = obj.getString("label");

                JSONArray indexArr = obj.getJSONObject("features").getJSONArray("indices");
                JSONArray valueArr = obj.getJSONObject("features").getJSONArray("values");

                int length = indexArr.size();
                String line = label + " ";
                Map<Integer, Double> indiceAndValue = new TreeMap<Integer, Double>();
                for (int i = 0; i < length; i++) {
                    indiceAndValue.put(indexArr.getInt(i), valueArr.getDouble(i));
//              line = line + indexArr.getInt(i)+":" + valueArr.getDouble(i) + " ";
                }

                //特征索引不能为0，不知为什么。
                if (indiceAndValue.containsKey(0)) {
                    indiceAndValue.remove(0);
                }

                for (Map.Entry<Integer, Double> m : indiceAndValue.entrySet()) {
                    line = line + m.getKey() + ":" + m.getValue() + " ";
                }
//          System.out.println(StringUtils.substring(line, 0, -1));
                FileUtils.write(libsvmFile, StringUtils.substring(line, 0, -1) + "\n", true);
            }
        }catch (IOException e){
            e.printStackTrace();
        }


        }
    }

